package com.hkpickup.web;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HtmlFetcher {
	private URL url;
	private String html = null;
	
	public HtmlFetcher(String urlStr){
		try {
			this.url = new URL(urlStr);
		} catch (MalformedURLException e) {
			this.url = null;
		}
	}
	
	public HtmlFetcher(URL url){
		this.url = url;		
	}
	
	
	public String getHtml(){
		return html;
	}
	
	public int fetch(){
		return fetch(null);
	}
	
	public int fetch(String charset){
		HttpURLConnection urlConnection=null;
//		URL url = new URL(urlStr);
		BufferedInputStream in = null;
		
		InputStreamReader insReader = null;
		BufferedReader buf = null;
		String html = null;
		int respondCode = -1; 
		try{
			// open httpconnection		
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setDoInput(true);
//			responseCode=urlConnection.getResponseCode();

			//System.out.println("end");
			in = new BufferedInputStream(urlConnection.getInputStream());			
			StringBuffer inBuffer = new StringBuffer();

			//get response data
			if (charset==null){
				insReader = new InputStreamReader(in );
			}else{
				insReader = new InputStreamReader(in, charset);
			}
			buf = new BufferedReader(insReader);
			int octet=0;
			while ((octet=buf.read())!=-1) {
				if (Character.isISOControl((char)octet)) {
					inBuffer.append(' ');
				} else {
					inBuffer.append((char)octet);
				}
			}
			html = inBuffer.toString();
		}catch (Exception ex){
			this.html= null;
			
		}finally{
			
			if (buf!=null)
				try {
					buf.close();
					if (insReader!=null) insReader.close();
					if (in!=null) in.close();
					if (urlConnection!=null){
						respondCode =  urlConnection.getResponseCode();
						urlConnection.disconnect();			
					}					
				} catch (IOException e) {
				}

		}
		this.html= html;
		return respondCode;
	}
	
}
